package cn.ingenic.glasssync.blmanager;

import java.util.List;

import android.bluetooth.BluetoothA2dp;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothProfile;
import android.bluetooth.peripheral.BluetoothHfDevice;
import android.content.Context;
import android.util.Log;

public class A2dpHfpUtil {
        private static String TAG = "A2dpHfpUtil";
	private static boolean DEBUG = true;
	private static A2dpHfpUtil sInstance;
	private Context mContext;
	private BluetoothAdapter mBTAdapter;
	private BluetoothA2dp mBluetoothA2dp;
        private BluetoothHfDevice mBluetoothHfDevice;
	private A2dpHfpUtil(Context context) {
		if (DEBUG)Log.i(TAG, "A2dpHfpUtil");
		mContext = context;
		mBTAdapter = BluetoothAdapter.getDefaultAdapter();
		if (mBTAdapter == null) {
			Log.e(TAG, "getDefaultAdapter fail");
			return;
		}		
		mBTAdapter.getProfileProxy(mContext, mProfileListener,
				BluetoothProfile.A2DP);
		if (BluetoothHfDevice.getProxy(mContext, mProfileListener)) {
		    Log.i(TAG, "BluetoothHfDevice getProxy() Success.");
		} else {
		    Log.i(TAG, "BluetoothHfDevice getProxy() Failed.");
		}
	}

	public static A2dpHfpUtil getInstance(Context c) {
		if (null == sInstance)
			sInstance = new A2dpHfpUtil(c);
		return sInstance;
	}

	private BluetoothProfile.ServiceListener mProfileListener = new BluetoothProfile.ServiceListener() {
		public void onServiceConnected(int profile, BluetoothProfile proxy) {
			if (DEBUG)
				Log.i(TAG, "onServiceConnected porfile="+profile);
			if (BluetoothProfile.HF_DEVICE == profile) {
			        mBluetoothHfDevice = (BluetoothHfDevice) proxy;
	                }else if (profile == BluetoothProfile.A2DP) {
				mBluetoothA2dp = (BluetoothA2dp) proxy;
			}
		}

		public void onServiceDisconnected(int profile) {
			if (DEBUG)
				Log.i(TAG, "onServiceDisconnected profile="+profile);
			if (profile == BluetoothProfile.HF_DEVICE) {
			    mBluetoothHfDevice = null;
			}
			if (profile == BluetoothProfile.A2DP) {
			    mBluetoothA2dp = null;
			}
		}
	};

	public void set_a2dp_disconnect() {
		if (mBluetoothA2dp == null) {
			Log.e(TAG, "have not get BluetoothA2dp service now!");
			return;
		}
		List<BluetoothDevice> listA2dp = mBluetoothA2dp.getConnectedDevices();
		if (DEBUG) {
			Log.i(TAG, "a2dp List<BluetoothDevice> listA2dp = " + listA2dp);
		}
		for (BluetoothDevice connectedBD : listA2dp) {
			mBluetoothA2dp.disconnect(connectedBD);
		}
	}

        public void set_hf_disconnect(){	    	    
	    if(mBluetoothHfDevice == null) {
		Log.e(TAG,"have not get BluetoothHfDevice");
		return;
	    }
	    List<BluetoothDevice> listHf =  mBluetoothHfDevice.getConnectedDevices();
	    if (DEBUG) 
		Log.d(TAG, "hfdevice List<BluetoothDevice> listHf = " + listHf);
	    for (BluetoothDevice connectedBD : listHf) {
		mBluetoothHfDevice.disconnect(connectedBD);
	    }
	}
}
